Reverse String
The most "popular" way of reversing a string in JavaScript is the following code fragment, which is quite common:
function reverseString(str) {
return str.split('').reverse().join('');
}
reverseString('string'); // "gnirts"
However, this will work only so long as the string being reversed does not contain surrogate pairs. Astral symbols, i.e. characters outside of the basic multilingual plane, may be represented by two code units, and will lead this naive technique to produce wrong results. Moreover, characters with combining marks (e.g. diaeresis) will appear on the logical "next" character instead of the original one it was combined with.
'?????.'.split('').reverse().join(''); //fails
While the method will work fine for most languages, a truly accurate, encoding respecting algorithm for string reversal is slightly more involved. One such implementation is a tiny library called Esrever, which uses regular expressions for matching combining marks and surrogate pairs in order to perform the reversing perfectly.
Explanation Section Explanation Result str The input string "string"
String.prototype.split( Splits string str into an array. The deliminator ) parameter "" means to split between each ["s","t","r","i","n","g"] character Array.prototype.reverse() Returns the array from the split string with its elements in reverse order. ["g","n","i","r","t","s"] Array.prototype.join( deliminator ) Joins the elements in the array together into a string. The "" parameter means an empty "gnirts" deliminator (i.e., the elements of the array are put right next to each other).
Using spread operator
function reverseString(str) {
return [...String(str)].reverse().join('');
}
console.log(reverseString('stackoverflow')); // "wolfrevokcats"
console.log(reverseString(1337)); // "7331"
console.log(reverseString([1, 2, 3])); // "3,2,1"
Custom reverse() function
function reverse(string) {
var strRev = "";
for (var i = string.length - 1; i >= 0; i--) {
strRev += string[i];
}
return strRev;
}
reverse("zebra"); // "arbez"